<template>
  <div class="page_space btn_space">
    <p class="title_1">被采样主体信息</p>
    <input-card>
      <inputItem title="经营主体" :content="params.intercourseEnterpriseName" />
      <inputItem title="主体类型" :content="params.subjectTypeText" />
      <inputItem
        v-if="params.subjectType != 'OtherSellersOfEdibleAgricultural'"
        title="所属市场"
        :content="params.managementEntName"
      />
    </input-card>

    <p class="title_1">基本信息</p>
    <input-card>
      <inputItem
        title="快检类型"
        tip="请选择快检类型"
        type="select"
        :content="params.inspectType"
        @select="toSelect(0)"
      />
      <inputItem
        title="采样人员"
        tip="请选择采样人员"
        type="select"
        :content="params.handlerName"
        @select="goto('/select-sampler')"
      />
      <inputItem
        title="采样日期"
        tip="请选择采样日期"
        type="select"
        :content="params.billDate"
        @select="toSelect(1)"
      />
    </input-card>

    <p class="title_1">样品信息</p>
    <input-card>
      <input-item-input
        v-model="params.details[0].businessVarietyCode"
        title="样品自编号（选填）"
        tip="请输入样品自编号"
        @blur="checkBusinessVarietyCode"
      />
      <inputItem
        title="样品名称"
        tip="请选择样品"
        type="select"
        :content="params.details[0].businessVarietyName"
        @select="goto('/select-sample')"
      />
      <input-item-number
        v-model="params.details[0].num"
        :unit="params.details[0].packUnitName"
        title="采样数量"
        tip="请输入采样数量"
        :unitList="['千克', '克']"
        @changeUnit="(e) => (params.details[0].packUnitName = e)"
      />
    </input-card>

    <p class="title_1">样品供货信息（选填）</p>
    <input-card v-if="params.details[0].intercourseEnterpriseName === ''">
      <div class="tip_add">
        <p>暂无供货信息</p>
        <button @click="addSupplyInfo">
          <span><span class="plus">+</span>添加供货信息</span>
        </button>
      </div>
    </input-card>
    <cardWrap v-else :title="params.details[0].intercourseEnterpriseName">
      <cardItem title="进货日期">{{ params.details[0].produceDate }}</cardItem>
      <cardItem title="进货数量"
        >{{ params.details[0].secondNum }}
        <span v-if="params.details[0].secondNum">千克</span></cardItem
      >
      <cardItem title="产地">{{ params.details[0].areaName }}</cardItem>
      <template #footer>
        <cardBtn
          leftText="删除"
          rightText="编辑"
          leftDanger
          @leftClick="deleteSampleInfo"
          @rightClick="editSampleInfo(params.details[0])"
        />
      </template>
    </cardWrap>

    <p class="title_1">备注与附件</p>
    <input-card class="attachment">
      <inputItem
        title="附件（选填）"
        tip="支持上传.png,.jpg文件,单个文件大小10M,最多上传5张"
        type="upload"
        @upload="(e) => (params.businessFileDTO = e)"
      />
      <input-item-textarea
        v-model="params.description"
        title="备注信息（选填）"
        tip="请输入备注"
        :textRows="4"
      />
    </input-card>

    <div class="btn_wrap">
      <button v-debounce class="btn middle default" @click="saveDraft">
        存草稿
      </button>
      <button v-debounce class="btn middle" @click="submit">提交</button>
    </div>

    <van-popup v-model="show" position="bottom" :round="true">
      <!-- 快检类型 -->
      <template v-if="active === 0">
        <van-picker
          ref="pickerForInspect"
          title="选择快检类型"
          show-toolbar
          :columns="['政府快检', '自检']"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="confirmInspectType">确定</button>
        </div>
      </template>

      <!-- 选择日期 -->
      <template v-if="active === 1">
        <van-datetime-picker
          v-model="currentDate"
          type="date"
          title="选择年月日"
          visible-item-count="3"
        />
        <div class="btn_box">
          <button class="btn large" @click="submitTime">确定</button>
        </div>
      </template>
    </van-popup>
  </div>
</template>

<script>
import inputCard from '@/components/input-card/card'
import inputItem from '@/components/input-card/item'
import inputItemInput from '@/components/input-card/item-input'
import inputItemNumber from '@/components/input-card/item-number'
import cardWrap from '@/components/base-card/wrap'
import cardItem from '@/components/base-card/item'
import cardBtn from '@/components/base-card/btn'
import { postSampling } from '@/api/subject'
import { ParseDate, delKeepaliveCache } from '@/utils'
import { store, mutations } from '@/observable'
import { validateNumberAndLetter } from '@/utils/validate'
import inputItemTextarea from '@/components/input-card/item-textarea'

export default {
  name: 'immediateSampling',
  components: {
    inputCard,
    inputItem,
    cardWrap,
    cardItem,
    cardBtn,
    inputItemInput,
    inputItemNumber,
    inputItemTextarea
  },
  data() {
    return {
      show: false,
      active: 0,
      currentDate: new Date(),
      params: {},
      varietyId: '' // 新增进货需要用到 样品id
    }
  },
  created() {
    console.log('页面created',this.$route.query)
    this.params = {
      intercourseEnterpriseId: '', // 经营主体id
      intercourseEnterpriseName: '', // 经营主体
      subjectTypeText: '', // 主体类型 中文
      managementEntName: '', // 所属市场
      subjectType: '', // TemporaryOperatingArea 市场内临时经营者； FixedPlace 市场内固定档口； OtherSellersOfEdibleAgricultural 市场外固定经营者
      // uscId: '440508600458992',
      // legalPerson: '吴举钿',
      placeId: '1', // 档口id
      description: '', // 备注
      inspectType: '', // 快检类型 中文
      uploadBizType: '', // 快检类型 政府快检：governmentCheck ， 自检：ownCheck
      handlerName: '', // 采样人员名称
      handlerId: '', // 采样人员id
      billDate: ParseDate(new Date()), // 采样日期
      type: 'SampleBill',
      actionCode: 'ACTION_DATA_CYTZ_TJ', // 草稿不一样
      state: 'ToBeChecked',
      businessFileDTO: [], // 上传文件
      businessFileDTOJson: '',
      details: [
        {
          // 样品字段
          businessVarietyCode: '', // 样品自编号
          businessVarietyName: '', // 样品名称
          businessVarietyId: '', // 样品id
          // 供货字段
          num: '', // 数量
          packUnitName: '千克',
          producer: '', // 进口 TRUE ; 国产 FALSE
          field10: '',
          relationBillDetailId: '',
          intercourseEnterpriseName: '',
          secondNum: '',
          originPlaceInfoName: '',
          areaName: '',
          produceDate: '',
          billNo: ''
        }
      ], // 样品信息
      detailsJson: ''
    }
  },
  beforeRouteLeave(to, from, next) {
    // 返回快检主体 清除缓存
    if (to.name === 'inspectionSubject' || to.name === 'subjectDetails') {
      mutations.setSampler({})
      mutations.setSample({})
      mutations.setSupplyInfo({})
      delKeepaliveCache(this)
      console.log('销毁:', to.name)
    }
    next()
  },
  activated() {
    console.log('页面activated')

    // 获取快检主体信息
    if (this.$route.query.intercourseEnterpriseInfo) {
      // 获取经营主体信息
      let info = JSON.parse(
        decodeURIComponent(this.$route.query.intercourseEnterpriseInfo)
      )
      this.params = { ...this.params, ...info }
    }
    // 获取-供货信息
    if (JSON.stringify(store.supplyInfo) !== '{}') {
      let info = store.supplyInfo
      console.log('供货：', info)
      for (let item in info) {
        this.params.details[0][item] = info[item] || ''
      }
    }
    // 获取-样品
    if (JSON.stringify(store.sampleInfo) !== '{}') {
      let info = store.sampleInfo
      this.params.details[0].businessVarietyName =
        info.businessVarietyName || ''
      this.params.details[0].businessVarietyId = info.businessVarietyId || ''
      this.varietyId = info.varietyId || ''
    }
    // 获取-采样人员
    if (JSON.stringify(store.samplerInfo) !== '{}') {
      let info = store.samplerInfo
      this.params.handlerName = info.handlerName || ''
      this.params.handlerId = info.handlerId || ''
    }
  },
  beforeDestroy() {

  },
  methods: {
    // 校验样品自编号输入
    checkBusinessVarietyCode(e) {
      console.log(e)
      if (!validateNumberAndLetter(e)) {
        this.$toast('样品自编号 格式不正确！')
        this.params.details[0].businessVarietyCode = ''
      }
    },
    // 添加供货信息
    addSupplyInfo() {
      // if (this.varietyId === '') {
      //   this.$toast('请先选择样品名称！')
      //   return false
      // }
      this.$router.push({
        name: 'addSupplyInfo',
        query: {
          intercourseEnterpriseId: this.params.intercourseEnterpriseId,
          varietyId: this.varietyId
        }
      })
    },
    // 校验
    validate() {
      // 必填项-基本信息
      let requiredOfBase = [
        {
          label: '快检类型',
          key: 'inspectType'
        },
        {
          label: '采样人员',
          key: 'handlerName'
        },
        {
          label: '采样日期',
          key: 'billDate'
        }
      ]
      // 必填项-样品
      let requiredOfSample = [
        {
          label: '样品名称',
          key: 'businessVarietyName'
        },
        {
          label: '采样数量',
          key: 'num'
        }
      ]
      try {
        requiredOfBase.forEach((item) => {
          let value = this.params[item.key].trim()
          if (value === '') {
            throw new Error(`${item.label} 为必填项！`)
          }
        })
        requiredOfSample.forEach((item) => {
          let value = this.params.details[0][item.key].trim()
          if (value === '') {
            throw new Error(`${item.label} 为必填项！`)
          }
        })

        // 正则校验
        // 校验样品自编号
        if (
          this.params.details[0].businessVarietyCode &&
          !validateNumberAndLetter(this.params.details[0].businessVarietyCode)
        ) {
          throw new Error(`样品自编号 格式不正确！`)
        }

        return true
      } catch (e) {
        this.$toast(e.message)
      }
    },
    toSelect(e) {
      this.active = e
      this.show = true
    },
    // 选择-快检类型
    confirmInspectType() {
      this.params.inspectType = this.$refs.pickerForInspect.getValues()[0]
      this.params.uploadBizType =
        this.params.inspectType === '政府快检' ? 'governmentCheck' : 'ownCheck'
      this.show = false
    },
    // 确定-进货时间
    submitTime() {
      this.params.billDate = ParseDate(this.currentDate)
      this.show = false
    },
    // 提交
    async submit() {
      // 验证各字段是否为空
      if (!this.validate()) return false

      this.params.state = 'ToBeChecked'
      this.params.actionCode = 'ACTION_DATA_CYTZ_TJ'
      this.params.businessFileDTOJson = JSON.stringify(
        this.params.businessFileDTO
      )
      // 判断是否留单位
      if (!this.params.details[0].num) this.params.details[0].packUnitName = ''
      this.params.detailsJson = JSON.stringify(this.params.details)
      // console.log(this.params)
      const { code } = await postSampling(this.params)
      if (code === '0') {
        this.$toast.success('提交成功')
        // 销毁组件
        delKeepaliveCache(this)
        this.$router.go(-1)
      }
    },
    // 保存草稿
    async saveDraft() {
      this.params.state = 'DRAFT'
      this.params.actionCode = 'ACTION_DATA_CYTZ_CWCG'
      this.params.businessFileDTOJson = JSON.stringify(
        this.params.businessFileDTO
      )
      this.params.detailsJson = JSON.stringify(this.params.details)
      // console.log(this.params)
      const { code } = await postSampling(this.params)
      if (code === '0') {
        this.$toast.success('提交成功')
        // 销毁组件
        delKeepaliveCache(this)
        this.$router.go(-1)
      }
    },
    // 删除-样品信息
    deleteSampleInfo() {
      this.$dialog
        .alert({
          title: '是否删除该信息?',
          showCancelButton: true
        })
        .then(async () => {
          for (let item in this.params.details[0]) {
            if (
              item === 'businessVarietyId' ||
              item === 'businessVarietyName' ||
              item === 'businessVarietyCode' ||
              item === 'num' ||
              item === 'packUnitName'
            ) {
              // 保留样品信息
              continue
            }
            this.params.details[0][item] = ''
          }
        })
        .catch(() => {
          // on cancel
        })
    },
    // 编辑-样品信息
    editSampleInfo(info) {
      this.$router.push({
        name: 'addSupplyInfo',
        params: {
          info: encodeURIComponent(JSON.stringify(info))
        },
        // 传 intercourseEnterpriseId 和 varietyId， 便于选择进货单号
        query: {
          intercourseEnterpriseId: this.params.intercourseEnterpriseId,
          varietyId: this.varietyId
        }
      })
    }
  }
}
</script>

<style scoped lang="scss"></style>
